package db

import (
	// "database/sql"
	"fmt"
	"log"
	"qianji"
	"qianji/configs"
	_ "github.com/go-sql-driver/mysql"
)

var DB *sql.DB

func Init() {
	dbConfig := utils.GlobalObject.AppConfig.DataBase
	if dbConfig.Name == "" || dbConfig.User == "" || dbConfig.Password == "" || dbConfig.IP == "" || dbConfig.Port == 0 {
		utils.Log.Info("no database")
		return
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		dbConfig.User,
		dbConfig.Password,
		dbConfig.IP,
		dbConfig.Port,
		dbConfig.Name,
	)

	var err error
	DB, err = sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("connect db failed: %v", err)
	}
	DB.SetMaxOpenConns(30)
	DB.SetMaxIdleConns(30)

	if err = DB.Ping(); err != nil {
		log.Fatalf("ping db failed: %v", err)
	}
	fmt.Println("db is connected")

	// 尝试查询一条数据
	var count int
	err = DB.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
	if err != nil {
		fmt.Printf("db query error: %v\n", err)
	} else {
		fmt.Printf("user count: %d\n", count)
	}

	user := dbobject.User{
		Name:     "test01",
		Password: "123456",
	}
	if err := dbobject.FindUserByNP(DB, &user); err != nil {
		fmt.Println("initDataBase FindUserByNP error:", err)
	}
}
